import { Dept } from '../api/Dept';
import { Room } from '../api/Room';
import { Card } from '../card/base/Card';

export class AIState {
	constructor(public dept: Dept) {
		this.dept.playerId = this.dept.deptId;
	}

	private timer: NodeJS.Timeout | null = null;

	turn(room: Room) {
		this.clear();
		var time = Math.floor(Math.random() * 2500);
		this.timer = setTimeout(() => {
			if (
				!this.dept.isAI ||
				!room.isStartGame ||
				room.turns.current() != this.dept.deptId
			)
				return;

			const cards = this.priority(room);
			if (cards.length > 0) {
				room.playCard(this.dept.playerId, cards[0].index, cards[0].target);
				this.turn(room);
			}
		}, time);
	}

	priority(room: Room): ICardRule[] {
		var cards: ICardRule[] = [];

		Object.values(this.dept.handCards).forEach((card, index) => {
			var data = { target: '', priority: -1 };

			var target = card.target(room, this.dept.deptId);
			switch (target) {
				case 'this':
					data.target = this.dept.deptId;
					data.priority = card.priority(
						room,
						this.dept.deptId,
						this.dept.deptId,
					);
					break;
				case 'all':
					data = this.target(room, card);
					break;
				default:
					data.target = target;
					data.priority = card.priority(room, this.dept.deptId, target);
					break;
			}

			// 检测花费
			if (card.costPoint(room, this.dept.deptId) > this.dept.point) {
				data.priority = -1;
			}

			// 检测花费
			var money = this.dept.getDeptDataValue('money');
			if (card.costMoney(room, this.dept.deptId) > money) {
				data.priority = -1;
			}

			if (card.cardId == 'NextTurn' || data.priority > -1)
				cards.push({ index, target: data.target, priority: data.priority });
		});
		
		return cards.sort((a: ICardRule, b: ICardRule) => {
			return b.priority - a.priority;
		});
	}

	target(room: Room, card: Card): { target: string; priority: number } {
		var data = { target: '', priority: -1 };
		Object.keys(room.depts).forEach((deptId) => {
			var priority = card.priority(room, this.dept.deptId, deptId);
			if (priority > data.priority) {
				data.target = deptId;
				data.priority = priority;
			}
		});
		return data;
	}

	clear() {
		if (this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
	}
}

interface ICardRule {
	index: number;
	target: string;
	priority: number;
}
